<?php

namespace app\wap\controller;

use app\common\controller\Mobile;
use app\common\model\Attachment;
use EasyWeChat\Factory;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 会员中心
 */
class User extends Mobile
{
    protected $noNeedLogin = ['login','autologin' ,'register', 'third','wechathandle','createmenu'];
    protected $noNeedRight = ['*'];
    protected $wechatApp = null;

    public function _initialize()
    {
        $this->layout='index';
        parent::_initialize();
        $auth = $this->auth;
    }

    public function wechathandle(){
        $oauth = $this -> wechatApp->oauth;
        $_user = $oauth -> user();
        $_userw = $this -> wechatApp -> user->get($_user['id']);
        Session::set('wechatUser',$_userw);
        $this->auth->loginByOpenid($_user['id']);

        $url = Session::get('redirectUrl') ?? url('/wap/index');
        $this -> redirect($url);
    }

    /**
     * 会员中心
     */
    public function index()
    {
       $this->redirect('/wap/index/index');
    }



    /**
     * 会员登录
     */
    public function login()
    {
        $deviceid = Session::get('deviceid') ?? 0;
        $url = $this->request->request('url', '');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('/wap/serviced?deviceid='.$deviceid));
        }
        if(empty($deviceid)){
            if(!empty($_SESSION['think']['redirectUrl'])){
                $device_url = str_replace('/wap/serviced?deviced=', ' ',$_SESSION['think']['redirectUrl']);
                $deviceid =  intval($device_url);
            }
        }
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile');
            $nickname = $this->request->post('nickname');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'mobile'   => 'require',
                'nickname'  => 'require',
            ];
            $msg = [
                'mobile.require'  => '手机号不能为空',
                'nickname.require' => '姓名不能为空',
            ];
            $data = [
                'mobile'   => $mobile,
                'nickname'  => $nickname,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            if ($this->auth->login($mobile, $nickname)) {
                $this->success(__('登录成功'), $url ? $url : url('/wap/serviced?deviceid='.$deviceid),['account'=>$mobile,'pwd'=>$nickname]);
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        // $referer = $this->request->server('HTTP_REFERER');
        // if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
        //     && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
        //     $url = $referer;
        // }
        // $this->view->assign('url', $url);
        $this->view->assign('title', __('登录'));
        return $this->view->fetch();
    }

    /**
     * 缓存自动登录·
     * [autologin description]
     * @return [type] [description]
     */
    public function autologin(){
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $nickname = $this->request->post('password');
            $deviceid = Session::get('deviceid') ?? 0;
            if ($this->auth->login($account, $nickname)) {
                $this->success(__('登录成功'),  url('/wap/serviced?deviced='.$deviceid));
            }else{
                $this->error('不允许登录');
            }
        }
    }
    /**
     * 退出登录
     */
    public function logout()
    {
        //退出本站
        $this->auth->logout();
//        $this->success(__('Logout successful'), url('wap/user/login'));
        return $this->view->fetch();
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
                'renewpassword.confirm' => __('Password and confirm password don\'t match')
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    public function attachment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['mimetype']) && preg_match("/[]\,|\*]/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = explode(',', $filterArr['mimetype']);
                    foreach ($mimetypeArr as $index => $item) {
                        if (stripos($item, "/*") !== false) {
                            $query->whereOr('mimetype', 'like', str_replace("/*", "/", $item) . '%');
                        } else {
                            $query->whereOr('mimetype', 'like', '%' . $item . '%');
                        }
                    }
                };
            }
            $model = new Attachment();
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $total = $model
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->count();

            $list = $model
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->limit($offset, $limit)
                ->select();
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
        return $this->view->fetch();
    }

    public function createmenu(){
        $menus = [
            'button' => [
                [
                    'name'=>'登记',
                    'type'=>'view',
                    'url' => 'https://ygym.cyqyfw.com/wap/resident/register'
                ],
                [
                    'name' => '凭证',
                    'type' => 'view',
                    'url' => 'https://ygym.cyqyfw.com/wap/resident/view'
                ],
                [
                    'name' => '疫苗动态',
                    'sub_button'    => [
                        [
                            'name' => '预约点信息',
                            'type' => 'view',
                            'url' => 'https://ygym.cyqyfw.com/wap/clinic/index'
                        ],
                        [
                            'name' => '通知',
                            'type' => 'view',
                            'url' => 'https://ygym.cyqyfw.com/wap/notice/index'
                        ]
                    ]
                ]
            ]
        ];

        $buttons = [
            [
                "type" => "view",
                "name" => "接种登记",
                "url"  => "https://ygym.cyqyfw.com/wap/resident/register",
            ],
            [
                "type" => "view",
                "name" => "登记凭证",
                "url"  => "https://ygym.cyqyfw.com/wap/resident/view",
            ],

             [
                 "name"       => "自助查询",
                 "sub_button" => [
                     [
                         "type" => "view",
                         "name" => "接种自查",
                         "url"  => "https://ygym.cyqyfw.com/wap/resident/point",
                     ],
                     [
                         "type" => "view",
                         "name" => "接种点查询",
                         "url"  => "https://ygym.cyqyfw.com/wap/clinic/index",
                     ],
                     [
                         "type" => "view",
                         "name" => "通知公告",
                         "url"  => "https://ygym.cyqyfw.com/wap/notice/index",
                     ],
                 ],
             ],
        ];

        $s = $this->wechatApp->menu->create($buttons);
        var_dump($s);
    }
}
